package org.kenewstar.common.utils;

import java.time.*;
import java.util.Date;

/**
 * 日期工具类
 * @author xinke.huang@hand-china.com
 * @version 1.0
 * @date 2021/3/11
 */
public class DateUtil {
    private static final long SECOND = 1000;
    private static final long MINUTE = 60 * SECOND;
    private static final long HOUR = 60 * MINUTE;
    private static final long DAY = 24 * HOUR;


    /**
     * 将当前时间与分享日期比较判断是否过期
     * @param date 分享日期
     * @param days 分享天数
     * @return 是否过期
     */
    public static boolean compareCurrentDatePass(Date date,Integer days){
        // 获取当前日期
        LocalDateTime current = LocalDateTime.now();
        LocalDateTime share = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

        if (days >= 0 && days < 30){
            LocalDateTime valid = share.plusDays(days);
            return valid.isBefore(current);
        } else if (days == 30){
            LocalDateTime valid = share.plusMonths(1);
            return valid.isBefore(current);
        } else {
            return false;
        }
    }

    /**
     * 获取还有多少天到期
     * @param date 分享日期
     * @param days 分享天数
     * @return 多久过期
     */
    public static String getCurrentDateValidTime(Date date,Integer days){
        if (days == -1){
            return "永久有效";
        }
        // 获取当前日期
        LocalDateTime current = LocalDateTime.now();
        LocalDateTime share = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime valid;
        if (days >0 && days <30){
            valid = share.plusDays(days);
        } else {
            valid = share.plusMonths(1);
        }
        long currentMilli = current.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long validMilli = valid.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        // 获取时间差
        long milli = validMilli - currentMilli;
        if (milli < 0){
            return "分享已失效";
        } else if (milli >= SECOND && milli < MINUTE) {
            return milli/SECOND + "秒钟后失效";
        } else if (milli >= MINUTE && milli < HOUR) {
            return milli/MINUTE + "分钟后失效";
        } else if (milli >= HOUR && milli < DAY) {
            return milli/HOUR + "小时后失效";
        } else if (milli >= DAY){
            return milli/DAY + "天后失效";
        }
        return "分享已失效";
    }
}
